<?php

namespace app\api\service\alipay;

use app\admin\model\Rechargerecord;
use app\admin\model\Member;

use think\Db;
use think\Exception;
use think\Loader;
use think\Log;

/**
 * 充值支付回调
 */
class RechargeNotify extends BaseNotify
{

    public function notify()
    {
        $data = $this->alipayNotify();

        // 写入日志
        $postXml = $this->arrayToXml($data);
        Log::record($postXml);

        // 验证签名
        if ($data['flag']) {
            Db::startTrans();
            try {
                $orderNo = $data['out_trade_no'];
                $Rechargerecord = new Rechargerecord();

                $order = $Rechargerecord->where('order_no', $orderNo)->find();
                if (!$order) {
                    Db::rollback();
                    Log::record('订单不存在');
                    return false;
                }

                // 更新用户余额
                $total_fee = $order['record_money'] + $order['gift_money'];
                $memberMdl = new Member();
                $memberUpdate = $memberMdl->where('id', $order['member_id'])->setInc('balance', $total_fee);
                if ($memberUpdate === false) {
                    echo 'fail';
                }

                // 更新订单状态
                $result = $Rechargerecord->where('order_no', $orderNo)->update(['status' => 1]);
                if($result === false){
                    Log::record('更新订单状态失败');
                    return false;
                }

                Db::commit();
                echo 'success';
            } catch (Exception $ex) {
                Db::rollback();
                Log::record($ex->getMessage());
                echo 'fail';
            }
        } else {
            echo 'fail';
        }
    }
}